package com.nettywork.code;

import com.entity.User;
import com.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取客户端发送的数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        ByteBuf byteBuf = ((ByteBuf)msg);
        byte[] b = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(b);
        User user = ProtostuffUtil.deserialize(b,User.class);
        System.out.println(user);
    }

    /**
     * 数据读取完毕之后的处理方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ByteBuf byteBuf = Unpooled.copiedBuffer("helloClient".getBytes(CharsetUtil.UTF_8));
//        ctx.write(byteBuf);
//        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
